package cn.neusoft.jdkproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkProxyFactory {
	Object target;

	public void setTarget(Object target) {
		this.target=target;
	}
	public Object getProxy() {
		return Proxy.newProxyInstance(
				target.getClass().getClassLoader(),
				target.getClass().getInterfaces(),
				new InvocationHandler() {
					@Override
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						String methodName=method.getName();
						if(methodName.contains("add")|| methodName.contains("update") ||
						methodName.contains("del")) {
							try{
								System.out.println("开启事务");
								Object result=method.invoke(target,args);
								System.out.println("提交事务");
								return result;
							} catch(Exception e) {
								System.out.println("回滚事务");
								return null;
							}finally {
								System.out.println("关闭事务");
							}
						} else if(methodName.contains("get")) {
							try{
								System.out.println("开启事务");
								Object result=method.invoke(target,args);
								System.out.println("提交事务");
								return result;
							} catch(Exception e) {
								System.out.println("回滚事务");
								return null;
							}finally {
								System.out.println("关闭事务");
							}
						} else {
							return method.invoke(target,args);
						}
 					}
				}
		);
	}
}
